<template>
  <span>
    <el-button size="small" class="is-circle" icon="el-icon-menu" @click="handleClick"> </el-button>
    <el-drawer
      :title="title"
      class="el-drawer__wrapper avue-dialog avue-crud__dialog avue-crud__column custom-dialog"
      :visible.sync="visible"
      :append-to-body="true"
      :size="'40%'"
      :modal-append-to-body="modalAppendToBody"
      @open="handleOpen"
      @opened="handleOpened"
      @close="handleClose"
      @closed="handleClosed"
    >
      <div class="dialog-content">
        <el-row>
          <el-col :span="8">
            <el-select v-model="selectOptions" multiple placeholder="请选择">
              <el-option v-for="item in optionsList" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-col>
        </el-row>
        <avue-crud
          v-if="visible"
          :option="option"
          :table-loading="loading"
          :data="data"
          ref="crud"
          @row-update="update"
          @row-del="del"
          @selection-change="selectionChange"
          @refresh-change="refreshChange"
          @on-load="onLoad"
        >
          <template slot="menuLeft">
            <el-button type="primary" size="small" icon="el-icon-plus" @click="openAddDialog">新 增 </el-button>
            <el-button type="danger" size="small" icon="el-icon-delete" @click="handleDelete">删 除 </el-button>
          </template>
        </avue-crud>
      </div>
      <footer class="footer">
        <el-button size="small" type="primary" @click="handleConfirm">确 定</el-button>
        <el-button size="small" @click="visible = false">取 消</el-button>
      </footer>
    </el-drawer>
    <el-dialog append-to-body title="选择扩展属性" :visible.sync="openAttributeDialog">
      <avue-crud
        v-if="openAttributeDialog"
        :option="attributeOption"
        :table-loading="attributeLoading"
        :page.sync="attributePage"
        :data="attributeData"
        ref="attributeCrud"
        @row-click="attributeRowClick"
        @search-change="attributeSearchChange"
        @search-reset="attributeSearchReset"
        @selection-change="selectionAttributeChange"
        @refresh-change="attributeRefreshChange"
        @on-load="onAttributeLoad"
      >
      </avue-crud>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="selectAttribute">选 择</el-button>
        <el-button size="small" icon="el-icon-circle-close" @click="openAttributeDialog = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog append-to-body title="属性编辑" :visible.sync="stagingDetailDialog">
      <avue-crud
        :option="stagingDetailOption"
        :data="stagingDetailData"
        :before-open="beforeOpen"
        ref="stagingDetailCrud"
        @row-update="stagingDetailUpdate"
        @row-del="stagingDetailDel"
      >
        <template slot-scope="{ row }" slot="isWeight">
          <el-tag :class="row.isWeight ? 'successTag' : 'dangerTag'">{{ row.isWeight === false ? '否' : '是' }}</el-tag>
        </template>
      </avue-crud>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="submitstagingDetail">保存</el-button>
        <el-button size="small" icon="el-icon-circle-close" @click="stagingDetailDialog = false">取消</el-button>
      </div>
    </el-dialog>
  </span>
</template>

<script>
/* eslint max-lines: "off" */ //临时豁免 关闭ESLint的最大代码行数max-lines规则
import { calcCascader } from '@/components/export-excel/util';
import { getList, add, remove, getPagePathList, getAttributeConfig } from '@/api/system/custom-attribute-config';
/*
 * appendToBody  modalAppendToBody  为element中属性
 *
 * */
export default {
  name: 'userTableConfig',
  inject: ['optionsList', 'crud'],
  data() {
    return {
      selectOptions: [],
      data: [],
      visible: false,
      loading: false,
      option: {
        height: 'calc(100vh - 287px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        delBtn: true,
        selection: true,
        dialogClickModal: false,
        menuWidth: 150,
        column: [
          {
            label: '名称',
            prop: 'lableCnName',
            width: 150,
            rules: [
              {
                required: true,
                message: '请选择名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '编码',
            prop: 'attributeKey',
            disabled: false,
            rules: [
              {
                required: true,
                message: '请选择编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '类型',
            prop: 'controlType',
            type: 'select',
            dicData: [
              {
                label: '单行文本',
                value: 'input'
              },
              {
                label: '数字',
                value: 'number'
              },
              {
                label: '时间',
                value: 'datetime'
              }
            ],
            disabled: false,
            rules: [
              {
                required: true,
                message: '请选择类型',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '默认值',
            prop: 'defaultValue'
          },
          {
            label: '排序',
            prop: 'sequence'
          },
          {
            label: '是否启用',
            prop: 'enabled',
            type: 'switch',
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ],
            value: false
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      },
      selectionList: [],
      openAttributeDialog: false,
      attributeLoading: false,
      attributeOption: {
        height: 500,
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        selection: true,
        dialogClickModal: false,
        menu: false,
        column: [
          {
            label: '属性名称',
            prop: 'lableCnName',
            width: 150,
            search: true
          },
          {
            label: '编码',
            prop: 'attributeKey',
            search: true
          },
          {
            label: '默认值',
            prop: 'defaultValue'
          },
          {
            label: '属性类型',
            prop: 'controlType',
            type: 'select',
            dicData: [
              {
                label: '单行文本',
                value: 'input'
              },
              {
                label: '数字',
                value: 'number'
              },
              {
                label: '时间',
                value: 'datatime'
              }
            ]
          },
          {
            label: '排序',
            prop: 'sequence'
          },
          {
            label: '是否启用',
            prop: 'enabled',
            type: 'switch',
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ],
            value: false
          },
          {
            label: '是否显示',
            prop: 'isShowed',
            type: 'switch',
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ],
            value: false
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      },
      attributeData: [],
      attributePage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      attributeQuery: {},
      selectionAttributeList: [],
      stagingDetailDialog: false,
      stagingDetailOption: {
        height: 500,
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        addBtn: false,
        editBtn: true,
        delBtn: true,
        selection: false,
        dialogClickModal: false,
        column: [
          {
            label: '名称',
            prop: 'lableCnName',
            width: 150,
            rules: [
              {
                required: true,
                message: '请选择名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '编码',
            prop: 'attributeKey',
            disabled: false,
            rules: [
              {
                required: true,
                message: '请选择编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '类型',
            prop: 'controlType',
            type: 'select',
            dicData: [
              {
                label: '单行文本',
                value: 'input'
              },
              {
                label: '数字',
                value: 'number'
              },
              {
                label: '时间',
                value: 'datetime'
              }
            ],
            disabled: false,
            rules: [
              {
                required: true,
                message: '请选择类型',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '默认值',
            prop: 'defaultValue'
          },
          {
            label: '排序',
            prop: 'sequence'
          },
          {
            label: '是否启用',
            prop: 'enabled',
            type: 'switch',
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ],
            value: false
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      },
      stagingDetailData: []
    };
  },
  computed: {
    propOption() {
      let result = [];
      function findProp(list = []) {
        if (!Array.isArray(list)) return;
        list.forEach((ele) => {
          if (Array.isArray(ele.children)) findProp(ele.children);
          else result.push(ele);
        });
      }
      findProp(this.columnOption);
      result = calcCascader(result);
      return result;
    },
    columnOption() {
      let column = this.option.column || [];
      return column;
    }
  },
  watch: {
    visible(val) {
      if (val) {
      }
    }
  },
  methods: {
    handleOpen() {
      this.$emit('open');
    },
    handleOpened() {
      this.$emit('opened');
    },
    handleClose() {
      this.$emit('close');
    },
    handleClosed() {
      this.$emit('closed');
    },
    handleClick() {
      this.visible = true;
    },
    handleConfirm() {
      this._forEach(this.selectOptions, (selectItem) => {
        console.log(selectItem, this.data);
        let column = [];
        this._forEach(this.data, (item) => {
          column.push({
            label: item.lableCnName,
            prop: item.attributeKey,
            type: item.controlType,
            value: item.defaultValue,
            dispaly: item.enabled
            // order: item.sequence
          });
        });
        console.log(this[selectItem].column);
        this.$emit('changeTable', { optionName: selectItem, column: column });
      });
      console.log(this.crud);
    },
    onLoad() {
      let path = this.$route.path;
      this.loading = true;
      getList(path).then((res) => {
        this.data = this._get(res, 'data.data', []);
        this.loading = false;
        this.selectionClear();
      });
    },
    update(row, index, done, loading) {
      add([row]).then(
        () => {
          this.onLoad();
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
        }
      );
    },
    del(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad();
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.detailIds);
        })
        .then(() => {
          this.onLoad();
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    openAddDialog() {
      this.openAttributeDialog = true;
    },
    onAttributeLoad(page, params = {}) {
      this.attributeLoading = true;
      getAttributeConfig(page.currentPage, page.pageSize, Object.assign(params, this.attributeQuery)).then((res) => {
        const data = res.data.data;
        this.attributePage.total = data.total;
        this.attributeData = data.records;
        this.attributeLoading = false;
      });
    },
    attributeRefreshChange() {
      this.onAttributeLoad(this.attributePage);
    },
    attributeRowClick(row) {
      if (this.attributeOption.selection) {
        this.$refs.attributeCrud.toggleRowSelection(row);
      }
    },
    attributeSearchChange(params, done) {
      this.attributeQuery = params;
      this.onAttributeLoad(this.attributePage);
      done();
    },
    attributeSearchReset() {
      this.attributeQuery = {};
      this.onAttributeLoad(this.attributePage);
    },
    selectionAttributeChange(list) {
      this.selectionAttributeList = list;
    },
    /**
     * 获取选择的模态框行数据
     */
    selectAttribute() {
      if (this.selectionAttributeList.length === 0) {
        this.$message.warning('请至少选择一条数据！');
        return;
      }
      this.stagingDetailDialog = true;
      this._forEach(this.selectionAttributeList, (item) => {
        item['attributeId'] = item.id;
        delete item.id;
        item.pagePath = this.$route.path;
        let saberTag = localStorage.getItem('saber-tag');
        item.pageName = JSON.parse(saberTag).content.label;
      });
      this.stagingDetailData = this._cloneDeep(this.selectionAttributeList);
    },
    stagingDetailUpdate(row, index, done, loading) {
      this.$set(this.stagingDetailData, [index], row);
      done();
    },
    stagingDetailDel(row, index) {
      this.stagingDetailData.splice(index, 1);
    },
    submitstagingDetail() {
      if (this.stagingDetailData.length === 0) {
        this.$message.warning('数据不能为空！');
        return;
      }
      let attributeKeyList = [];
      this._forEach(this.detailData, (item) => {
        this._forEach(this.stagingDetailData, (rowDataItem) => {
          if (item.attributeKey === rowDataItem.attributeKey) {
            attributeKeyList.push(rowDataItem.attributeKey);
          }
        });
      });
      if (attributeKeyList.length > 0) {
        this.$message.error(`列表中已存在如下编码${attributeKeyList.join('，')}的属性`);
        return;
      }
      add(this.stagingDetailData).then(
        () => {
          this.stagingDetailDialog = false;
          this.openAttributeDialog = false;
          this.onLoad();
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        },
        (error) => {}
      );
    }
  }
};
</script>

<style lang="scss">
.custom-dialog {
  top: 0px;
  overflow: hidden;
  .dialog-content {
    overflow-x: hidden;
    overflow-y: scroll;
    height: calc(100vh - 152px);
  }
}
.footer {
  height: 52px;
  position: relative;
  left: 0px;
  bottom: 0px;
  display: flex;
  align-items: center;
  align-content: center;
  flex-wrap: nowrap;
}

.avue-dialog .el-drawer__body {
  overflow: hidden;
}

.is-circle {
  border-radius: 15%;
  box-shadow: 2px 2px 4px 0 rgba(0, 0, 0, 0.12), 0 0 6px 0 rgba(0, 0, 0, 0.04);
}
</style>
